<template>
	<treeselect v-model="deptId" :appendToBody="true" :default-expand-level="5" :options="deptOptions"
		:clearable="false" :isDefaultExpanded="true" :show-count="true" :placeholder="tips" :style="'width:' + width"
		@select="change" :disabled="able" :disable-branch-nodes="branchNodes" :normalizer="normalizer" :flat="true" />

</template>

<script>
	import {
		listDept
	} from "@/api/system/dept";
	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";
	import Cookies from "js-cookie";
	export default {
		components: {
			Treeselect
		},
		props: {
			level: {
				type: Number,
				default: 3
			},
			/**
			 * 在清除所有输入字段之前进行处理的函数。
			 * 返回"false"以防止清除值
			 * @type {function(): (boolean|Promise<boolean>)}
			 */
			normalizercx: {
				type: Boolean,
				default: false,
			},

			tips: {
				type: String,
				default: '请选择部门'
			},
			width: {
				type: String,
				default: '220px'
			},
			able: {
				type: Boolean,
				default: false
			},
			branchNodes: {
				type: Boolean,
				default: false
			},
			id: {
				type: String,
				default: null
			}
		},
		data() {
			return {
				deptOptions: [],
				deptId: this.id
			}
		},
		created() {
			this.getDeptList();
		},
		methods: {
			/** 查询部门列表 */
			getDeptList() {
				listDept().then(response => {
					// 转换为treeselect需要的格式
					const rows = Array.isArray(response.rows) ? response.rows : (Array.isArray(response.data) ? response.data : []);
					this.deptOptions = this.formatDeptOptions(rows);
					if (this.deptOptions.length > 0) {
						// 设置默认选中第一个部门的ID
						this.deptId = this.deptOptions[0].id;
						this.$emit('deptCallback', this.deptOptions[0]);
						var dept = {
							"id": this.deptOptions[0].id,
							"label": this.deptOptions[0].label
						}
						Cookies.set("selDeptData", JSON.stringify(dept));
					}
				});
			},
			// 格式化部门数据为treeselect需要的格式
			formatDeptOptions(depts) {
				return depts.map(item => {
					return {
						id: item.deptId || item.id,
						label: item.deptName || item.label
					};
				});
			},
			normalizer(node) {
				if (this.normalizercx) {
					// 部门节点不需要禁用逻辑，所以可以移除这部分
				}
			},
			change(val, data) {
				this.$emit('deptCallback', val);
				var dept = {
					"id": val.id,
					"label": val.label
				}
				Cookies.set("selDeptData", JSON.stringify(dept));
			},
			// 清空选择
			clear() {
				this.deptId = null
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>